package com.sdyeda.readiot.config;

import java.io.BufferedReader;
import java.io.FileReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import oshi.SystemInfo;

public class License {
	
	public static boolean isVilid() {
		Date now = new Date();
		if(Setting.Get(Setting.ISREGISTERED)!=null && (boolean)Setting.Get(Setting.ISREGISTERED)==true && now.before((Date)Setting.Get(Setting.VALID_TIME))) {
			return true;
		}
		else {
			return false;
		}
	}

	public static String getLicenseInfo() {
		String info = "注册信息\n\n";
		info = info + "机器编码："+ new SystemInfo().getHardware().getDiskStores().get(0).getSerial()+"\n";
		info = info + "有效时间："+  new SimpleDateFormat("yyyy-MM-dd",Locale.CHINA).format(Setting.Get(Setting.VALID_TIME))+"\n";
		if(isVilid()) {
			info = info + "已注册！\n";
		}
		else {
			info = info + "未注册或时间到期，请联系厂商注册！\n\n";
		}
		return info;
	}
	//获取协议，设置有效时间
	static boolean getLicense() {
		String licstr = "";

		try {
			FileReader fr = new FileReader(Setting.LicenseFile);
			try (BufferedReader br = new BufferedReader(fr)) {
				licstr = br.readLine();
			}
		} catch (Exception e) {
		}
		if (licstr == null || licstr == "") {
			licstr = (String)Setting.Get(Setting.LicenseStr);
		}
		if (licstr == null || licstr == "") {
			return false;
		}
		licstr = licstr.trim();

		//补充Base64结尾   =
		int n = licstr.length();
		int sub = 0;
		if(n/4*4 != n) {
			sub = (n/4+1)*4 - n;
		}
		for(int i=0;i<sub;i++) {
			licstr = licstr + "=";
		}
		//System.out.println(licstr);
		String declic = DESUtil.getDecryptString(licstr);
		if (declic == null) {
			return false;
		}
		//System.out.println(declic);

		//硬盘序列号  //去除前后的空格。可能会存在。
		String hdserial = new SystemInfo().getHardware().getDiskStores().get(0).getSerial().trim();
		if (declic.contains("sn:" + hdserial)) {
			int off = declic.indexOf("validtime:");
			if (off == -1) {
				return false;
			}
			
			off=off+"validtime:".length();
			//System.out.println(off);

			String validtime = declic.substring(off);
			//System.out.println(validtime);
			Date valid;
			try {
				valid = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA).parse(validtime);
				Setting.Set(Setting.VALID_TIME, valid);
				return true;
			} catch (Exception e) {
				return false;
			}
		}
		return false;
	}
	

}
